package response

import (
	"github.com/gin-gonic/gin"
	"net/http"
)

type Response struct {
	Code int
	Data interface{}
	Msg  string
	Err  error
}

func Error(err error) Response {
	return Response{
		Msg:  "请求失败,服务器发生错误",
		Data: map[string]interface{}{},
		Code: FAIL,
		Err:  err,
	}
}

const (
	FAIL = -1
	OK   = 0
)

func JSONResult(code int, data interface{}, msg string) Response {
	return Response{
		Code: code,
		Data: data,
		Msg:  msg,
	}
}

func Ok() Response {
	return JSONResult(OK, map[string]interface{}{}, "操作成功")
}

func OkWithMessage(message string) Response {
	return JSONResult(OK, map[string]interface{}{}, message)
}

func OkWithData(data interface{}) Response {
	return JSONResult(OK, data, "操作成功")
}

func OkWithDetailed(data interface{}, message string) Response {
	return JSONResult(OK, data, message)
}

func Fail() Response {
	return JSONResult(FAIL, map[string]interface{}{}, "操作失败")
}

func FailWithMessage(message string) Response {
	return JSONResult(FAIL, map[string]interface{}{}, message)
}

func FailWithDetailed(data interface{}, message string) Response {
	return JSONResult(FAIL, data, message)
}

func JSON(ctx *gin.Context, resp Response) {
	// 响应客户端
	ctx.JSON(http.StatusOK, gin.H{
		"code": resp.Code,
		"msg":  resp.Msg,
		"data": resp.Data,
	})
}
